<template>
  <div class="app-container">
    <div class="mb10">
      <el-button type="success" icon="el-icon-plus" @click="handleAdd"> 添加 </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      size="mini"
    >
      <el-table-column label="#" type="index" width="50" />
      <el-table-column label="姓名" prop="name" />
      <el-table-column label="电话" prop="mobile" />
      <el-table-column label="邮箱" prop="email" />
      <el-table-column label="角色" prop="role">
        <template slot-scope="{ row }">{{ roleKV[row.role] }}</template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
          />
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDelete(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="m-center">
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="fetchList"
      />
    </div>

    <!-- 编辑 -->
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      width="500px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="角色" prop="role" required>
          <el-select v-model="temp.role" placeholder="请选择类型">
            <el-option
              v-for="item in roleOptions"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="服务专员" prop="userId" required>
          <el-select
            v-model="temp.userId"
            placeholder="请选择服务专员"
            filterable
            clearable
          >
            <el-option
              v-for="item in usersList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="isEdit ? update() : add()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryServiceOfficer,
  addServiceOfficer,
  modifyServiceOfficer,
  viewServiceOfficer,
  deleteServiceOfficer,
} from "@/api/client";
import { fetchList as getUsers } from "@/api/user";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
const defaultForm = {
  role: "",
  userId: "",
  customerId: "",
};

export default {
  name: "ClientDetail",
  components: { Pagination },
  filters: {},
  computed: {
    roleKV: function () {
      return this.roleOptions.reduce((acc, cur) => {
        acc[cur.key] = cur.value;
        return acc;
      }, {});
    },
  },
  data() {
    return {
      tableData: [],
      total: 0,
      listQuery: {
        customerId: "",
        limit: 10,
        page: 1,
      },
      roleOptions: [
        { key: "0", value: "客户经理" },
        { key: "1", value: "结算财务" },
      ],
      temp: Object.assign({}, defaultForm),
      dialogVisible: false,
      usersList: [],
      rules: {},
      isEdit: false,
      listLoading: false,
    };
  },

  created() {
    const id = this.$route.params && this.$route.params.id;
    if (id) {
      this.listQuery.customerId = parseInt(id);
      this.temp.customerId = parseInt(id);
      this.getUsers();
      this.fetchList();
    }
  },
  methods: {
    // 得到列表
    async fetchList() {
      this.listLoading = true;
      queryServiceOfficer(this.listQuery).then((response) => {
        this.tableData = response.data.items;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    async getUsers() {
      getUsers({ page: 1, limit: 100 }).then((response) => {
        this.usersList = response.data.items;
      });
    },
    // 搜索
    handleFilter() {
      this.listQuery.page = 1;
      this.fetchList();
    },
    // 重置数据
    resetTemp() {
      this.temp = Object.assign({}, defaultForm);
      this.temp.customerId = this.listQuery.customerId;
    },
    handleAdd() {
      this.resetTemp();
      this.dialogVisible = true;
      this.isEdit = false;
    },
    add() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          addServiceOfficer(this.temp).then((response) => {
            this.$message.success("添加成功");
            this.dialogVisible = false;
            this.fetchList();
          });
        }
      });
    },
    handleUpdate(row) {
      this.viewServiceOfficer(row.id);
    },
    viewServiceOfficer(id) {
      viewServiceOfficer({ id }).then((response) => {
        this.temp = Object.assign(this.temp, response.data);

        this.isEdit = true;
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      });
    },
    // 修改
    update() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          modifyServiceOfficer(this.temp).then((response) => {
            this.$message.success("修改成功");
            this.dialogVisible = false;
            this.fetchList();
          });
        }
      });
    },
    // 删除
    handleDelete(row) {
      this.$confirm(`你确定要删除【${row.name}】吗?`, "提示", {
        type: "warning",
      })
        .then(() => {
          deleteServiceOfficer({ id: row.id }).then(() => {
            this.$message.success("删除成功");
            this.fetchList();
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
  },
};
</script>
